package hot100;

import java.util.Arrays;
import java.util.LinkedList;
import java.util.List;
import java.util.stream.Collectors;

public class Solution297 {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        StringBuilder stringBuilder = new StringBuilder("[");
        if (root == null) {
            stringBuilder.append("null");
            return stringBuilder.toString();
        }
        stringBuilder.append(serialize(root.left));
        stringBuilder.append(serialize(root.right));
        stringBuilder.append("]");
        return stringBuilder.toString();
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        data = data.substring(1, data.length() - 1);
        LinkedList<String> split = Arrays.stream(data.split(",")).collect(Collectors.toCollection(LinkedList::new));
        return deserialize(split);

    }
    public TreeNode deserialize(LinkedList<String> list) {
        if (list.pop().equals("null")) {
            return null;
        }
        TreeNode root = new TreeNode(Integer.parseInt(list.pop()));
        root.left = deserialize(list);
        root.right = deserialize(list);
        return root;
    }

}
